/**
 * Copyright 2011 rkehoe
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 */
package queryable.store.util;

import java.util.Date;

/**
 * @author rkehoe
 */
public class Stopwatch {

	public static final int MS_IN_SEC =1000;
	public static final int MS_IN_MIN =60*MS_IN_SEC;
	public static final int MS_IN_HR =60*MS_IN_MIN;
	
	private String task;
	/**
	 * @param string
	 */
	public Stopwatch(String task) {
		this.task = task;
	}

	private Date startTime;
	private Date endTime;
	private long elapsedTimeMillis;

	public Stopwatch() {

	}

	public Stopwatch start() {
		startTime = new Date();
		return this;
	}

	public Stopwatch stop() {
		endTime = new Date();
		elapsedTimeMillis = endTime.getTime() - startTime.getTime();
		return this;
	}

	public long getElapsedTimeMillis() {
		return this.elapsedTimeMillis;
	}

	public long getElapsedTimeSecs() {
		return this.elapsedTimeMillis / 1000;
	}

	public double getElapsedTimeMinutes() {
		return this.getElapsedTimeSecs() / 60.0;
	}

	public double getElapsedTimeHours() {
		return this.getElapsedTimeMinutes() / 60.0;
	}

	public void printElapsedTime() {
		int ms = (int) this.getElapsedTimeMillis();
		int hrs = ms/MS_IN_HR;
		ms=ms-(hrs*MS_IN_HR);
		int min = ms/MS_IN_MIN;
		ms=ms-(min*MS_IN_MIN);
		int sec = ms/MS_IN_SEC;
		ms=ms-(sec*MS_IN_SEC);
		
		StringBuffer sb = new StringBuffer();
		if(hrs>0){
			sb.append(" "+hrs+" hrs");
			if(min+sec>0) {sb.append(":");}
		}
		if(min>0){
			sb.append(" "+min+" min");
			if(sec>0) {sb.append(":");}
		}
		if(sec>0){
			sb.append(" "+sec+" sec");
			if(ms>0) {sb.append(":");}
		}
		sb.append(" "+ms+" ms");
		System.out.println(this.task+" completed in ("+this.getElapsedTimeMillis()+") "+sb.toString());		
	}

	/**
     * @param num_distinct_entities
     */
    public void printRate(int numEntities)
    {
    	long elapsedTimeSecs = this.getElapsedTimeMillis();
    	int rate = (int) ((numEntities/(double)elapsedTimeSecs)*1000);
    	System.out.println("Rate = "+rate+" per Sec.");
		System.out.println("Rate = "+rate*60+" per Min.");			    
		System.out.println("Rate = "+rate*60*60+" per Hour.");
    }

	/**
     * @param string
     * @return
     */
    public static Stopwatch instance(String string)
    {
	    return new Stopwatch(string);
    }
}